from flask import render_template, Blueprint, request, jsonify

from models import db
from models.host import Host, HostGroup
from service.authtoken import login_required

index_route = Blueprint('index', __name__)


@index_route.route('/')
@login_required
def index():
    return render_template('index.html')


@index_route.route('/host', methods=["GET", "POST", "PUT", "DELETE"])
@login_required
def host():
    if request.method == "GET":
        host_id = request.args.get("host_id")
        if host_id:
            host_obj = Host.query.filter(Host.id == host_id).first()
            host_group_item = {
                "id": host_obj.id,
                "name": host_obj.name,
                "ip": host_obj.ip,
                "port": host_obj.port,
                "username": host_obj.username,
                "password": host_obj.password,
                "auth_type": host_obj.auth_type,
                "host_group_id": host_obj.host_group_id
            }
            return jsonify(code=0, data=host_group_item)
        else:
            host_list = []
            for host_group_obj in HostGroup.query.all():
                host_group_item = {
                    "id": host_group_obj.id,
                    "name": host_group_obj.name,
                    "hosts": [],
                }

                for host_obj in host_group_obj.hosts:
                    host_group_item["hosts"].append({
                        "id": host_obj.id,
                        "name": host_obj.name
                    })

                host_list.append(host_group_item)

            return jsonify(code=0, data=host_list)
    elif request.method == "POST":
        request_data = request.get_json()
        if request_data is None:
            return jsonify(code=3, msg="未接收到参数!")

        try:
            host_name = request_data.get("name")
            host_obj = Host(name=host_name)
            host_obj.ip = request_data.get("ip")
            host_obj.port = request_data.get("port")
            host_obj.username = request_data.get("username")
            host_obj.password = request_data.get("password")
            host_obj.auth_type = request_data.get("auth_type")
            host_obj.host_group_id = request_data.get("host_group_id")
            db.session.add(host_obj)
            db.session.commit()
            return jsonify(code=0, msg="主机创建成功!")
        except Exception:
            db.session.rollback()
            return jsonify(code=1, msg="主机创建失败!")
    elif request.method == "PUT":
        request_data = request.get_json()
        if request_data is None:
            return jsonify(code=3, msg="未接收到参数!")

        host_id = request_data.get("id")
        try:
            fields = {
                "name": request_data.get("name"),
                "ip": request_data.get("ip"),
                "port": request_data.get("port"),
                "username": request_data.get("username"),
                "password": request_data.get("password"),
                "auth_type": request_data.get("auth_type"),
                "host_group_id": request_data.get("host_group_id"),
            }
            Host.query.filter(Host.id == host_id).update(fields)
            db.session.commit()
            return jsonify(code=0, msg="主机修改成功!")
        except Exception :
            db.session.rollback()
            return jsonify(code=1, msg="主机修改失败!")
    elif request.method == "DELETE":
        request_data = request.get_json()
        if request_data is None:
            return jsonify(code=3, msg="未接收到参数!")

        id_list = request_data.get("id_list")
        try:
            Host.query.filter(Host.id.in_(id_list)).delete()
            db.session.commit()
            return jsonify(code=0, msg='删除主机成功!')
        except Exception as e:
            db.session.rollback()
            return jsonify(code=1, msg='删除主机失败!')


@index_route.route('/hostgroup', methods=["GET", "POST", "PUT", "DELETE"])
@login_required
def host_group():
    if request.method == "GET":
        group_id = request.args.get("group_id")
        if group_id:
            host_group_obj = HostGroup.query.filter(HostGroup.id == group_id).first()
            host_group_item = {
                "id": host_group_obj.id,
                "name": host_group_obj.name,
            }
            return jsonify(code=0, data=host_group_item)
        else:
            host_group_list = []
            for host_group_obj in HostGroup.query.all():
                host_group_list.append({
                    "id": host_group_obj.id,
                    "name": host_group_obj.name,
                })
            return jsonify(code=0, data=host_group_list)
    elif request.method == "POST":
        request_data = request.get_json()
        if request_data is None:
            return jsonify(code=3, msg="未接收到参数!")

        try:
            group_name = request_data.get("name")
            host_group_obj = HostGroup(name=group_name)
            db.session.add(host_group_obj)
            db.session.commit()
            return jsonify(code=0, msg="主机组创建成功!")
        except Exception as e:
            print(e)
            db.session.rollback()
            return jsonify(code=1, msg="主机组创建失败!")
    elif request.method == "PUT":
        request_data = request.get_json()
        if request_data is None:
            return jsonify(code=3, msg="未接收到参数!")

        group_id = request_data.get("id")
        group_name = request_data.get("name")
        try:
            HostGroup.query.filter(HostGroup.id == group_id).update({"name": group_name})
            db.session.commit()
            return jsonify(code=0, msg="主机组修改成功!")
        except Exception:
            db.session.rollback()
            return jsonify(code=1, msg="主机组创建失败!")
    elif request.method == "DELETE":
        request_data = request.get_json()
        if request_data is None:
            return jsonify(code=3, msg="未接收到参数!")

        id_list = request_data.get("id_list")
        try:
            hosts = False
            for host_group_obj in HostGroup.query.filter(HostGroup.id.in_(id_list)):
                if len(host_group_obj.hosts) != 0:
                    hosts = True

            if not hosts:
                HostGroup.query.filter(HostGroup.id.in_(id_list)).delete()
                db.session.commit()
                return jsonify(code=0, msg='删除主机组成功!')
            else:
                return jsonify(code=1, msg='删除主机组失败，主机组中还包含有主机!')
        except Exception as e:
            print(e)
            db.session.rollback()
            return jsonify(code=1, msg='删除主机组失败!')
